// +----------------------------------------------------------------------
// | CmsWing [ 美业管理系统 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016 psi All rights reserved.
// +----------------------------------------------------------------------
// | Author: huang <2374266244@qq.com>
// +----------------------------------------------------------------------
'use strict';
import Base from './base.js';

export default class extends Base {

	async factorylistAction(){
		let page = this.post();
		let pages = page.pages;
		let limits = page.limits;
		let search = page.search;
		let zt = page.zt;
		let shopid = this.shop_userinfo.departmentid;

		let data = await this.model('or_factory')
				.where({shopid: shopid, isdisabled: zt, 'name|remarks':['like','%'+search+'%']})
				.page(pages, limits)
				.order('id DESC')
				.countSelect();

		return this.json(data);

	}
	
	// 添加、编辑厂商
	async addeditAction(){
		let data = this.post();
		// 取出shopid和departmentid
		let shopid = this.shop_userinfo.departmentid
		let addtime = Math.round(new Date().valueOf()/1000);
		if (data.id*1) {
			let gengxin = await this.model('or_factory').where({id:data.id}).update({name:data.name, remarks:data.remarks});
			return gengxin?this.success('编辑成功'):this.fail('编辑失败');
		} else {
			data.shopid = shopid;
			data.departmentid = await this.model('or_department').where({id: shopid}).getField('pid', true)
			data.addtime = addtime;
			let res = await this.model('or_factory').add(data);
			return res?this.success('添加成功'):this.fail('添加失败');
		}
	}

	// 弃用启用厂家
	async unstopAction(){
		let id = this.post('id');
		let st = this.post('st');
		let res = await this.model('or_factory').where({id:id}).update({isdisabled:st});
		if (st*1) return res?this.success('关闭成功'):this.fail('关闭失败');
		else return res?this.success('重启成功'):this.fail('重启失败');
	}

	// 获取厂商包括机构和店家的
	async getAllFactoryListAction () {
		let filter = this.get()
		let shopid = this.shop_userinfo.departmentid

		// 获取departmentid
		let departmentid = await this.model('or_department').where({id: shopid}).getField('pid', true)
		let where = {}
		where['_complex'] = {
			departmentid: departmentid,
			shopid: shopid,
			_logic: 'OR'
		}
		where['isdisabled'] = 0
		where['name|remarks'] = ['like','%' + filter.search + '%']

		let data = await this.model('or_factory')
		.where(where)
		.page(filter.pages, filter.limits)
		.order('id DESC')
		.countSelect()

		return this.json(data)
	}

}